from http.server import BaseHTTPRequestHandler
from http import HTTPStatus

from SessionManager import SessionManager

import logging
logger = logging.getLogger(__name__)

class GeneralRequestHandler(BaseHTTPRequestHandler):
    def __init__(self, request, client_address, server):
        # If there is any init job important to each member function
        # It should be done before supper().__init__
        # Because the root parent BaseRequestHandler will call member function in its __init__
        logger.debug("[GeneralRequestHandler.GeneralRequestHandler]")
        super().__init__(request, client_address, server)

        logger.debug(f"request = {request}")
        logger.debug(f"client_address = {client_address}")
        logger.debug(f"server = {server}")

    def do_GET(self):
        logger.debug("[GeneralRequestHandler.do_GET]")

        cmd, params = self._parseRequest()
        if cmd is None:
            return

        handled, status, length, result = SessionManager().HandleRequest(self._handleRequst, cmd, params)
        if not handled:
            logger.debug(f"Handle Error: {result}")
            self._handleError(status, result)
            return

        self.send_response(status)
        self.send_header("Content-type", "text/html; charset=utf-8")
        self.send_header("Content-Length", length)
        self.end_headers()
        self.wfile.write(result)

    def do_POST(self):
        logger.debug("[GeneralRequestHandler.do_POST]")
        self.send_error(HTTPStatus.NOT_IMPLEMENTED)

    def do_HEAD(self):
        logger.debug("[GeneralRequestHandler.do_HEAD]")
        self.send_error(HTTPStatus.NOT_IMPLEMENTED)

    def _parseRequest(self):
        logger.debug(f"[GeneralRequestHandler.parseRequest] {self.requestline}")
        return "cmd", "params"

    def _handleRequst(self, cmd, params):
        r = []
        r.append("<!DOCTYPE HTML>")
        r.append("<html>")
        r.append("<body>")
        r.append("Hello PServer!")
        r.append("</body>")
        r.append("</html>")
        encoded = "\n".join(r).encode("utf-8", "surrogateescape")
        return True, HTTPStatus.OK, str(len(encoded)), encoded

    def _handleError(self, status, error):
        self.send_error(status, error)
        logger.error(error)
